package com.opal.system.controller;


import com.opal.consts.CommonConst;
import com.opal.domain.ReturnMessageData;
import com.opal.system.entity.table.OpalHrorg;
import com.opal.system.entity.table.OpalRole;
import com.opal.system.entity.table.OpalUser;
import com.opal.system.service.OpalRoleService;
import com.opal.system.service.OpalUserService;
import com.opal.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class OpalUserController {
	
	@Autowired
	private OpalUserService opalUserService;
	@Autowired
	private OpalRoleService opalRoleService;

	@RequestMapping("/user/login")
	@ResponseBody
	public ReturnMessageData login(String loginName, String loginPwd, HttpServletRequest request) {
		log.info("北京时间："+CommonUtils.getCurrentDateTimeString()+"、ip地址："+request.getRemoteAddr()+"使用用户：【"+loginName+"】进行登陆操作");
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(loginName, loginPwd);
		ReturnMessageData rmd= null;
		try {
			subject.login(token);
			OpalUser principal = (OpalUser) subject.getPrincipal();
			//principal.setUserPassword(null);
			subject.getSession().setAttribute(CommonConst.OPALUSER, principal);
			subject.getSession().setAttribute(CommonConst.USERID, principal.getUserId());
			log.info("用户：【"+principal.getUserName()+"】在ip地址："+request.getRemoteAddr()+"的时间段"+ CommonUtils.getCurrentDateTimeString() +"中登陆");
		} catch (UnknownAccountException e) {
			// e.printStackTrace();
			System.out.println("账户不存在");
			rmd = new ReturnMessageData(500,"账户不存在");
			// thymeleaf 转发方式格式：forward:login.html
			//return "forward:/user/login.html";
			return rmd;
		} catch (IncorrectCredentialsException e) {
			System.out.println("密码不正确");
			rmd = new ReturnMessageData(500,"密码不正确");
			//return "forward:/user/login.html";
			return rmd;
		}
		rmd = new ReturnMessageData(200,"");
		return rmd;
	}
	
	@RequestMapping("/user/tologin")
	@ResponseBody
	public String tologin() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "<script>window.location.href = \"/login.html\";</script>";
		//return "{\"out\":406}";
	}

	/**
	 * 根据当前用户获取组织
	 * @return
	 */
	@RequestMapping("/user/getUserOrgHrorg")
	@ResponseBody
	public List<OpalHrorg> getUserOrgHrorg(HttpServletRequest request){
		List<OpalHrorg> list=opalUserService.getUserOrgHrorgService(request);
		return list;
	}


	/**
	 * 获取用户所有信息
	 * @return
	 */
	@RequestMapping("/manage/user/selectalluser")
	@ResponseBody
	public List<OpalUser> selectAllUser() {
		List<OpalUser> users= opalUserService.selectAllUserService();
		return users;
	}

	/**
	 * 获取用户所有信息:为easyui的tree准备数据
	 * @return
	 */
	@RequestMapping("/manage/user/selectalluserTree")
	@ResponseBody
	public Object selectAllUserTree(String userName) {
		Object users= opalUserService.selectAllUserTreeService(userName);
		return users;
	}

	/**
	 * 获取用户所有信息:为layui的tree准备数据
	 * @return
	 */
	@RequestMapping("/manage/user/selectAllUserLayuiTable")
	@ResponseBody
	public Object selectAllUserLayuiTree(String username) {
		Object users= opalUserService.selectAllUserLayuiTableService(username);
		return users;
	}

	/**
	 * 根据条件获取用户信息
	 * @return
	 */
	@RequestMapping("/manage/user/selectConditionUser")
	@ResponseBody
	public Object selectConditionUser(OpalUser opalUser, Integer page,Integer rows) {
		Object users= opalUserService.selectConditionUserService(opalUser,page,rows);
		return users;
	}

	/**
	 * 添加用户
	 * @param opalUser
	 * @param roleId
	 * @return
	 */
	@RequestMapping("/manage/user/addUser")
	@ResponseBody
	public ReturnMessageData addUser(OpalUser opalUser,long[] roleId) {
		ReturnMessageData rmd=	opalUserService.addUserService(opalUser,roleId);
		return rmd;
	}

	/**
	 * 验证旧密码是否正确
	 * @param password
	 * @return
	 */
	@RequestMapping("/user/getPassword")
	@ResponseBody
	public ReturnMessageData getPassword(String password) {
		ReturnMessageData rmd=	opalUserService.getPasswordService(password);
		return rmd;
	}

	/**
	 * 用户修改密码
	 * @param oldPassword
	 * @param newPassword
	 * @param newPassword2
	 * @return
	 */
	@RequestMapping("/user/selfModifyPassword")
	@ResponseBody
	public Object selfModifyPassword(String oldPassword,String newPassword,String newPassword2) {
		ReturnMessageData rmd=	opalUserService.selfModifyPasswordService(oldPassword,newPassword,newPassword2);
		return rmd;
	}

	/**
	 * 修改用户
	 * @param opalUser
	 * @param roleId
	 * @return
	 */
	@RequestMapping("/manage/user/updateuser")
	@ResponseBody
	public ReturnMessageData updateUser(OpalUser opalUser,long[] roleId) {
		ReturnMessageData rmd=	opalUserService.updateUserService(opalUser,roleId);
		return rmd;
	}

	/**
	 * 获取组织
	 * @return
	 */
	@RequestMapping("/manage/user/selectallhrorg")
	@ResponseBody
	public Object selectAllHrorg() {
		ReturnMessageData rmd=	opalUserService.selectAllHrorgService();
		return rmd.getData();
	}

	/**
	 * 删除用户
	 * @param opalUser
	 * @return 数组权限id
	 */
	@RequestMapping("/manage/user/deleteuser")
	@ResponseBody
	public ReturnMessageData deleteUser(@RequestBody OpalUser[] opalUser) {
		ReturnMessageData roleid=	opalUserService.deleteUserService(opalUser);
		return roleid;
	}

	/**
	 * 根据用户id查询当前角色
	 * @param userId
	 * @return 数组权限id
	 */
	@RequestMapping("/manage/user/findByUserIdRole")
	@ResponseBody
	public Object findByUserIdRole(long userId) {
		Object[] roleid=opalUserService.findByUserIdRoleService(userId);
		return roleid;
	}

	/**
	 * 根据用户id更换角色
	 * @param map
	 * @return 数组权限id
	 */
	@RequestMapping("/manage/user/updateByUserIdRole")
	@ResponseBody
	public Object updateByUserIdRole(@RequestBody Map<String,Object> map) {
		Object result=opalUserService.updateByUserIdRoleService(map);
		return result;
	}

	/**
	 * 查询所有角色2:用于树形
	 * @return
	 */
	@RequestMapping("/manage/role/selectallrole2")
	@ResponseBody
	public List<Map<String,Object>> selectAllrole2() {
		List<OpalRole> opalRole= opalRoleService.selectAllrole();
		List<Map<String,Object>> result= new ArrayList<>();
		for (OpalRole o:opalRole){
			Map<String,Object> map = new HashMap<>();
			map.put("id",o.getRoleId());
			map.put("text",o.getRoleName());
			map.put("roleDescreption",o.getRoleDescreption());
			result.add(map);
		}
		return result;
	}

	@RequestMapping("user/{page}")
	public String skipIndex(@PathVariable("page") String page) {
		return page;
	}

	@RequestMapping("{page}")
	public String skipPage(@PathVariable("page") String page) {
		return page;
	}

}
